package cn.yitun.chat.yitunservercommonlib.context;


import cn.yitun.chat.yitunservercommonlib.basebean.web.JwtUserDto;
import cn.yitun.chat.yitunservercommonlib.basebean.web.RequestInfoDto;
import cn.yitun.chat.yitunservercommonlib.basebean.web.WebsockJwtUserDto;
import cn.yitun.chat.yitunservercommonlib.constant.Constants;

import java.util.HashMap;
import java.util.Map;

public class FilterContextHandler {
    private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();
    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    /**
     * 常规http 请求用户 三次请求
     */
    public static JwtUserDto getJwtUserDto() {
        Object value = get(Constants.CURRENT_LOGIN_USER);
        return (JwtUserDto)value;
    }
    /**
     * websock 连接用户
     */
    public static WebsockJwtUserDto getWebsockJwtUserDto() {
        Object value = get(Constants.CURRENT_WEBSOCK_USER);
        return (WebsockJwtUserDto)value;
    }

    public static RequestInfoDto getRequestInfoDto() {
        Object value = get(Constants.REQUEST_INFO);
        return (RequestInfoDto)value;
    }
    public static String getToken() {
        Object value = get(Constants.TOKEN);
        return returnObjectValue(value);
    }

    /**
     * 常规http 请求用户 三次请求
     */
    public static void setJwtUserDto(JwtUserDto userDto) {
        set(Constants.CURRENT_LOGIN_USER , userDto);
    }
    /**
     * websock 连接用户
     */
    public static void setWebsockJwtUserDto(WebsockJwtUserDto userDto) {
        set(Constants.CURRENT_WEBSOCK_USER , userDto);
    }

    public static void setRequestInfoDto(RequestInfoDto requestInfoDto) {
        set(Constants.REQUEST_INFO , requestInfoDto);
    }

    public static void setToken(String token){
        set(Constants.TOKEN , token);
    }

    private static String returnObjectValue(Object value) {
        return value == null ? null : value.toString();
    }

    public static void remove() {
        threadLocal.remove();
    }

}
